﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Collections;
using ImageShaperLib;
using ImageShaperLib.Tools;

namespace ImageShaper
{
    public partial class MainForm : Form
    {

        #region 公共变量
        public static System.Windows.Forms.StatusBarPanel sbpMain;
        public static System.Windows.Forms.StatusBarPanel sbpSize;
        public static System.Windows.Forms.StatusBarPanel sbpHandPoint;
        public static System.Windows.Forms.StatusBarPanel sbpUpdates;
        public static ImageShaper.ElementData ElementData = new ElementData();
        private System.Windows.Forms.MenuItem mnuLayersNewLayer;
        public static ImageShaperLib.FileTypeCollection fileTypes = InitFileTypes();

        //状态栏
        private System.Windows.Forms.StatusBar sbGlobal;
        //选项对话框
       // public ImageShaper.WinGUI.Dialogs.OptionDialog optDialog;
       // public ImageShaper.WinGUI.Dialogs.ToolsDialog toolsDialog;
        public ImageShaper.WinGUI.Dialogs.LayersDialog layersDialog;
       // public ImageShaper.WinGUI.Dialogs.HistoryDialog historyDialog;

        //模拟剪贴板，在程序中保存复制的Layer
        public static Layer copyedLayer = null;
        private System.Windows.Forms.MenuItem menuItem1;
        private System.Windows.Forms.MenuItem menuItem2;
        private System.Windows.Forms.MenuItem menuItem4;
        private System.Windows.Forms.MenuItem menuItem6;
        private System.Windows.Forms.MenuItem mnuFileAcquireFromClipboard;
        private System.Windows.Forms.MenuItem mnuImageFlip;
        private System.Windows.Forms.MenuItem mnuImageResize;
        private System.Windows.Forms.MenuItem mnuImageRotate;
        private System.Windows.Forms.MenuItem menuItem19;
        private System.Windows.Forms.MenuItem menuItem20;
        private System.Windows.Forms.MenuItem menuItem7;
        private System.Windows.Forms.MenuItem menuItem9;
        private System.Windows.Forms.MenuItem mnuEditEraseSelection;
        private System.Windows.Forms.MenuItem mnuEditInvertSelection;
        private System.Windows.Forms.MenuItem mnuEditDeselect;
        private System.Windows.Forms.MenuItem menuItem17;
        //模拟历史
        public static ArrayList historyList = null;
        private System.Windows.Forms.MenuItem mnuViewStatusBar;
        private System.Windows.Forms.ToolBarButton tbbActualSize;
        //颜色拾取器
        //public static ImageShaperLib.Tools.ColorPicker colorPicker = new ImageShaperLib.Tools.ColorPicker();

        /// <summary>
        /// 初始化文件类型集合
        /// </summary>
        /// <returns></returns>
        private static ImageShaperLib.FileTypeCollection InitFileTypes()
        {
            ArrayList ft = new ArrayList();

            ft.Add(ImageShaperLib.FileTypes.Pdn);
            ft.Add(ImageShaperLib.FileTypes.Bmp);
            ft.Add(ImageShaperLib.FileTypes.Jpeg);
            ft.Add(ImageShaperLib.FileTypes.Png);
            ft.Add(ImageShaperLib.FileTypes.Tiff);
            ft.Add(ImageShaperLib.FileTypes.Gif);

            return new ImageShaperLib.FileTypeCollection(ft);
        }

        #endregion

        #region "私有变量"
        private PrintDocument pd;
        private PrintDialog printDialog;
        private PrintPreviewDialog printPreviewDialog;
        #endregion
        public MainForm()
            : this(new string[0])
        {
        }

        public MainForm(string[] args)
        {
         
            // Windows 窗体设计器支持所必需的
            InitializeComponent();

            // 初始化状态栏
            StartupStatusBar();
          
            //
            // 初始化绘图环境
            //

            if (args != null && args.Length >= 1)
            {
               // this.isOpenFirst = true;
               // this.firstFile = args[0];
            }
        }

        /// <summary>
        /// 创建状态栏
        /// </summary>
        private void StartupStatusBar()
        {
            sbGlobal = new System.Windows.Forms.StatusBar();
            sbpMain = new System.Windows.Forms.StatusBarPanel();
            sbpUpdates = new System.Windows.Forms.StatusBarPanel();
            sbpSize = new System.Windows.Forms.StatusBarPanel();
            sbpHandPoint = new System.Windows.Forms.StatusBarPanel();
            ((System.ComponentModel.ISupportInitialize)(sbpMain)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(sbpUpdates)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(sbpSize)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(sbpHandPoint)).BeginInit();
            // 
            // sbGlobal
            // 
            sbGlobal.Visible = true;
            sbGlobal.Location = new System.Drawing.Point(0, 405);
            sbGlobal.Name = "sbGlobal";
            sbGlobal.Panels.AddRange(new System.Windows.Forms.StatusBarPanel[] {
																						sbpMain,
																						sbpUpdates,
																						sbpSize,
																						sbpHandPoint});
            sbGlobal.ShowPanels = true;
            sbGlobal.Size = new System.Drawing.Size(608, 22);
            sbGlobal.TabIndex = 1;
            // 
            // sbpMain
            // 
            sbpMain.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Spring;
            sbpMain.Text = "需要帮助请按F1键";
            sbpMain.Width = 562;
            // 
            // sbpUpdates
            // 
            sbpUpdates.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Contents;
            sbpUpdates.Width = 10;
            // 
            // sbpSize
            // 
            sbpSize.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Contents;
            sbpSize.Width = 10;
            // 
            // sbpHandPoint
            // 
            sbpHandPoint.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Contents;
            sbpHandPoint.Text = "Point:";
            sbpHandPoint.Width = 10;

            this.Controls.Add(this.sbGlobal);
            ((System.ComponentModel.ISupportInitialize)(sbpMain)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(sbpUpdates)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(sbpSize)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(sbpHandPoint)).EndInit();
        }



        /// <summary>
        /// 点击工具栏
        /// </summary>
        private void ToolBarHandle(object sender, ToolBarButtonClickEventArgs e)
        {
            if (e.Button == tbbNew)
                //this.New();
                this.Open();
            if (e.Button == tbbOpen)
                this.Open();
            if (e.Button == tbbSave)
                this.Save();
            if (e.Button == this.tbbPrint)
                this.Print();
            if (e.Button == this.tbbPrintPreview)
                this.PrintPreview();
            if (e.Button == this.tbbZoomIn)
                this.ZoomOut();
            if (e.Button == this.tbbZoomOut)
                this.ZoomIn();
            if (e.Button == this.tbbClearBg)
                this.ClearBackground();
            if (e.Button == this.tbbCompare)
                this.CompareChannel();
            if (e.Button == this.tbbRetangle)
                this.DrawRetangle();
            if (e.Button == this.tbbElipese)
                this.DrawElipese();
        }


        #region 自定义事件

        /// <summary>
        /// 创建新图象
        /// </summary>
        private void New()
        {
            //ImageShaper.WinGUI.Dialogs.NewImageDialog nid = new ImageShaper.WinGUI.Dialogs.NewImageDialog(this);
            //nid.ShowDialog();
        }

        /// <summary>
        /// 打开文件
        /// </summary>
        private void Open()
        {
            string fileName;
            DialogResult result = ChooseFile(out fileName);

            if (result == DialogResult.OK)
            {
                DoOpenFile(fileName);
            }
            else
                return;
        }

        /// <summary>
        /// 打开文件
        /// </summary>
        /// <param name="filename">文件名称</param>
        public void DoOpenFile(string filename)
        {
            if (filename == null)
            {
                throw new ArgumentNullException("文件名为空!");
            }
            else
                if (!File.Exists(filename))
                {
                    throw new Exception("您选择的文件不存在!");
                }
            ImageShaperLib.Document doc = ImageShaperLib.Document.Deserialize(filename);
            if (doc == null)
            {
                return;
            }
            else
            {
                try
                {
                    ImageShaper.WinGUI.Forms.ImageForm imageForm = new ImageShaper.WinGUI.Forms.ImageForm(this);
                    imageForm.Show();
                    imageForm.GetView().GetSurfaceBox().Document = doc;
                    this.layersDialog.BindLayerList(doc.Layers);
                }
                catch (Exception ex)
                {
                   // MessageBox.Show(ex.Message);
                }
            }
        }

        /// <summary>
        /// 选择文件
        /// </summary>
        /// <param name="fileName">返回值Filename</param>
        /// <returns>返回DialogResult</returns>
        private DialogResult ChooseFile(out string fileName)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.CheckFileExists = true;
            ofd.CheckPathExists = true;
            ofd.Multiselect = false;
            ofd.RestoreDirectory = true;

            ofd.Filter = fileTypes.ToString(true, "All images");
            ofd.FilterIndex = 0;

            DialogResult result = ofd.ShowDialog(this);
            fileName = ofd.FileName;

            return result;
        }

        /// <summary>
        /// 从粘贴板获取文档
        /// </summary>
        private void AcquireFromClipboard()
        {
            IDataObject iData = Clipboard.GetDataObject();
            if (iData == null)
                return;
            Image img = null;
            if (iData.GetDataPresent(DataFormats.Bitmap) || iData.GetDataPresent(DataFormats.MetafilePict))
            {
                img = (Image)iData.GetData(DataFormats.Bitmap);
                ImageShaper.WinGUI.Forms.ImageForm imageForm = new ImageShaper.WinGUI.Forms.ImageForm(this);
                ImageShaperLib.Document doc = new ImageShaperLib.Document(img);
                doc.IsDirty = true;
                imageForm.GetView().GetSurfaceBox().Document = doc;
                this.layersDialog.BindLayerList(imageForm.GetView().GetSurfaceBox().Document.Layers);
                imageForm.Show();
            }
        }

        /// <summary>
        /// 打开最近
        /// </summary>
        /// <param name="filename"></param>
        private void OpenRecent(string filename)
        {

        }

        /// <summary>
        /// 保存文档
        /// </summary>
        private void Save()
        {
            if (this.ActiveMdiChild == null)
                return;

            ((ImageShaper.WinGUI.Forms.ImageForm)this.ActiveMdiChild).Save();
        }

        /// <summary>
        /// 另存为
        /// </summary>
        private void SaveAs()
        {
            if (this.ActiveMdiChild == null)
                return;
            ((ImageShaper.WinGUI.Forms.ImageForm)this.ActiveMdiChild).SaveAs();
        }

        /// <summary>
        /// 打印
        /// </summary>
        private void Print()
        {
            try
            {
                if (PrinterSettings.InstalledPrinters.Count <= 0)
                {
                    MessageBox.Show("您的电脑上未安装任何打印机，请先安装打印机在进行打印！", "打印", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    return;
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("您的电脑上未启动打印服务，请先到系统服务中启动！", "打印", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }
            if (this.ActiveMdiChild == null)
                return;
            this.pd.DocumentName = ((ImageShaper.WinGUI.Forms.ImageForm)this.ActiveMdiChild).GetView().GetSurfaceBox().Document.Name;
            printDialog.Document = this.pd;
            printDialog.AllowSelection = true;
            printDialog.AllowSomePages = true;

            try
            {
                if (printDialog.ShowDialog() == DialogResult.OK)
                    this.pd.Print();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "打印");
            }
        }

        /// <summary>
        /// 打印预览
        /// </summary>
        private void PrintPreview()
        {
            try
            {

                if (PrinterSettings.InstalledPrinters.Count <= 0)
                {
                    MessageBox.Show("您的电脑上未安装任何打印机，请先安装打印机在进行打印！", "打印", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    return;
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("您的电脑上未启动打印服务，请先到系统服务中启动！", "打印", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }
            if (this.ActiveMdiChild == null)
                return;

            this.printPreviewDialog.Document = this.pd;
            this.printPreviewDialog.UseAntiAlias = true;
            this.printPreviewDialog.ShowDialog();
        }

        /// <summary>
        /// 打印设置
        /// </summary>
        private void PrintSetting()
        {
            if (PrinterSettings.InstalledPrinters.Count <= 0)
            {
                MessageBox.Show("您的电脑上未安装任何打印机，请先安装打印机在进行打印！", "打印", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }
            if (this.ActiveMdiChild == null)
                return;
            PageSetupDialog psd = new PageSetupDialog();
            psd.Document = this.pd;
            psd.ShowDialog();
        }

        /// <summary>
        /// 程序退出
        /// </summary>
        private void Exit()
        {
            this.Close();
            Application.Exit();
        }

        /// <summary>
        /// 撤销
        /// </summary>
        private void Undo()
        {

        }

        /// <summary>
        /// 重复
        /// </summary>
        private void Redo()
        {

        }

        /// <summary>
        /// 剪贴
        /// </summary>
        private void Cut()
        {

        }

        /// <summary>
        /// 复制
        /// </summary>
        private void Copy()
        {
        }

        /// <summary>
        /// 粘贴
        /// </summary>
        private void Paste()
        {
          
        }

        /// <summary>
        /// 粘贴到新图层
        /// </summary>
        private void PastetoNewLayer()
        {
           
        }

        /// <summary>
        /// 清除
        /// </summary>
        private void EraseSelection()
        {

        }

        /// <summary>
        /// 全选
        /// </summary>
        private void SelectAll()
        {
        }

        /// <summary>
        /// 工具栏显示
        /// </summary>
        private void ToolsBar()
        {
            this.mainToolBar.Visible = !this.mainToolBar.Visible;
        
        }

        /// <summary>
        /// 工具栏状态
        /// </summary>
        private void StatusBar()
        {
           
        }

        /// <summary>
        /// 标尺设置
        /// </summary>
        private void Ruler()
        {
            if (this.ActiveMdiChild == null)
                return;
            ((ImageShaper.WinGUI.Forms.ImageForm)this.ActiveMdiChild).GetView().RulerShow =
                !((ImageShaper.WinGUI.Forms.ImageForm)this.ActiveMdiChild).GetView().RulerShow;
          
        }

        /// <summary>
        /// 网格
        /// </summary>
        private void Grids()
        {
            if (this.ActiveMdiChild == null)
                return;
            ((ImageShaper.WinGUI.Forms.ImageForm)this.ActiveMdiChild).GetView().GridsShow =
                !((ImageShaper.WinGUI.Forms.ImageForm)this.ActiveMdiChild).GetView().GridsShow;
            
        }

        /// <summary>
        /// 缩小
        /// </summary>
        private void ZoomIn()
        {
            if (this.ActiveMdiChild == null)
                return;
            ImageShaperLib.ScaleFactor sf = ((ImageShaper.WinGUI.Forms.ImageForm)this.ActiveMdiChild).GetView().ScaleFactor.GetNextLarger();
            if (sf.Numerator > 8 && sf.Denominator == 1)
            {
            }
            else
            {
                ((ImageShaper.WinGUI.Forms.ImageForm)this.ActiveMdiChild).GetView().ScaleFactor = sf;
            }
        }

        /// <summary>
        /// 放大
        /// </summary>
        private void ZoomOut()
        {
            if (this.ActiveMdiChild == null)
                return;
            ImageShaperLib.ScaleFactor sf = ((ImageShaper.WinGUI.Forms.ImageForm)this.ActiveMdiChild).GetView().ScaleFactor.GetNextSmaller();
            if (sf.Numerator > 8 && sf.Denominator == 1)
            {
            }
            else
            {
                ((ImageShaper.WinGUI.Forms.ImageForm)this.ActiveMdiChild).GetView().ScaleFactor = sf;
            }
        }

        /// <summary>
        /// 实际大小
        /// </summary>
        private void ActualSize()
        {
            if (this.ActiveMdiChild == null)
                return;
            ((ImageShaper.WinGUI.Forms.ImageForm)this.ActiveMdiChild).GetView().ScaleFactor =
                new ImageShaperLib.ScaleFactor(1, 1);
        }

        /// <summary>
        /// 扣除空白
        /// </summary>
         private void ClearBackground()
        {
            if (this.ActiveMdiChild == null)
                return;
            MessageBox.Show("当前没有正在编辑的图像！请打开一幅图像或创建一幅图像再执行创建Layer！", "ImageShaper", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            return;
 
        }



        CuttingRectangle cutRect, cutRect2, cutRect3, cutRect4;
        /// <summary>
        /// 移轨
        /// </summary>
         private void CompareChannel()
        {
            if (this.ActiveMdiChild == null)
                return;
            if (cutRect != null)
                return;
  
            cutRect = new CuttingRectangle(new System.Drawing.Rectangle(10, 10, 100, 100));
            cutRect.SetPictureBox((ImageShaper.WinGUI.Forms.ImageForm)this.ActiveMdiChild);

            cutRect2 = new CuttingRectangle(new System.Drawing.Rectangle(110, 10, 100, 100));
            cutRect2.SetPictureBox((ImageShaper.WinGUI.Forms.ImageForm)this.ActiveMdiChild);


            cutRect3 = new CuttingRectangle(new System.Drawing.Rectangle(210, 10, 100, 100));
            cutRect3.SetPictureBox((ImageShaper.WinGUI.Forms.ImageForm)this.ActiveMdiChild);

            cutRect4 = new CuttingRectangle(new System.Drawing.Rectangle(310, 10, 100, 100));
            cutRect4.SetPictureBox((ImageShaper.WinGUI.Forms.ImageForm)this.ActiveMdiChild);
        }

        /// <summary>
        /// 画矩形
        /// </summary>
        private void DrawRetangle()
        {
            ElementData.ElementType = ElementType.Rectangle;
        }

        /// <summary>
        /// 画椭圆
        /// </summary>
         private void DrawElipese()
        {
            ElementData.ElementType = ElementType.Ellipse;
        }

        /// <summary>
        /// 新图层
        /// </summary>
        private void NewLayer()
        {
            if (this.ActiveMdiChild == null)
            {
                MessageBox.Show("当前没有正在编辑的图像！请打开一幅图像或创建一幅图像再执行创建Layer！", "ImageShaper", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }
            ImageShaper.WinGUI.Dialogs.NewLayerDialog nld = new ImageShaper.WinGUI.Dialogs.NewLayerDialog(this);
            nld.ShowDialog();
        }

      
        /// <summary>
        /// 属性设置
        /// </summary>
        private void Properties()
        {
            ImageShaper.WinGUI.Dialogs.PropertiesForm propertiesForm = new ImageShaper.WinGUI.Dialogs.PropertiesForm();
            propertiesForm.ShowDialog();
        }

        /// <summary>
        /// 图像获取
        /// </summary>
        private void PicCapture()
        {
            //ImageShaper.WinGUI.Forms.Form1 form1 = new ImageShaper.WinGUI.Forms.Form1();
            //form1.MdiParent = this;
            //form1.Show();
        }

        /// <summary>
        /// 加载Album
        /// </summary>
        private void LoadAlbum()
        {
            string album = Path.Combine(Application.StartupPath, "Album.exe");
            if (File.Exists(album))
            {
                try
                {
                    System.Diagnostics.Process.Start(album);
                    this.WindowState = FormWindowState.Minimized;
                }
                catch (Exception ex)
                {
                    this.WindowState = FormWindowState.Maximized;
                    MessageBox.Show(ex.Message);
                }
            }
            else
                return;
        }


        [Description("当活动文档被改变时要求保存文件")]
        public static DialogResult AskForSaveDocument()
        {
            return MessageBox.Show("当前文档已经更改!您需要保存吗?",
                Application.ProductName, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
        }

        private void Help()
        {
            MessageBox.Show("帮助文件未完成！", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void UpdateSoftware()
        {
            MessageBox.Show("此项服务暂时未开通！", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void AboutDialog()
        {
            MessageBox.Show("此项服务暂时未开通！", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information); 
        }


        #endregion


    }
}
